/**
 * <b>项目名：</b>hclv-web<br/>
 * <b>包名：</b>com.flea.hclv.service.impl<br/>
 * <b>文件名：</b>HHotelServiceImpl.java<br/>
 * <b>版本信息：</b>1.0<br/>
 * <b>日期：</b>2018年9月12日 下午3:50:38<br/>
 * <b>COPYRIGHT 2010-2012 ALL RIGHTS RESERVED 虫子科技</b>-版权所有<br/>
 */
package com.flea.hclv.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flea.hclv.constant.Const;
import com.flea.hclv.constant.HConstant;
import com.flea.hclv.model.dao.*;
import com.flea.hclv.model.entity.*;
import com.flea.hclv.model.entity.vo.ProductSearchVo;
import com.flea.hclv.model.entity.vo.ProductTripVo;
import com.flea.hclv.service.*;
import com.flea.hclv.util.HclvDictUtil;
import com.flea.hclv.util.ServerResponse;
import com.flea.system.base.util.StringUtil;
import com.flea.system.bean.FleaPage;
import com.flea.system.dao.OrgUserMapper;
import com.flea.system.dao.WebFileuploadMapper;
import com.flea.system.entity.OrgDept;
import com.flea.system.entity.OrgUser;
import com.flea.system.entity.WebDict;
import com.flea.system.entity.WebFileupload;
import com.flea.system.platform.session.FleaOrgUtils;
import com.flea.system.utils.FleaStringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @description TODO
 * @createTime 2018年9月12日 下午3:50:38
 * @modifyTime
 * @author myflea@163.com
 * @version 1.0
 */
@Service("productService")
public class HProductServiceImpl implements HProductService {

  Logger logger = LoggerFactory.getLogger(HProductServiceImpl.class);

  @Autowired
  private HProductMapper productMapper;
  @Autowired
  private HAddressMapper addressMapper;
  @Autowired
  private HlineSpotRelationMapper lineSpotRelationMapper;
  @Autowired
  private HLineMapper hLineMapper;
  @Autowired
  private OrgUserMapper orgUserMapper;

  @Autowired
  private HSpotMapper spotMapper;
  @Autowired
  private HAddressMapper hAddressMapper;

  @Autowired
  private HTripService tripService;
  @Autowired
  private HTripSpotRelationService tripSpotRelationService;
  @Autowired
  private HTimeTableService timetableService;
  @Autowired
  private HExplainService explainService;
  @Autowired
  private HResourceRelationService resourceRelationService;
  @Autowired
  private WebFileuploadMapper webFileuploadMapper;

  @Override
  public FleaPage<HProduct> findForGird(int curPage, int pageSize,String model,HttpServletRequest request) {
    ProductSearchVo svo = new ProductSearchVo();
    if(!StringUtil.isEmpty(model)){
      svo = JSONObject.parseObject(model,ProductSearchVo.class);
    }
    //不为空就进行查询数据库，根据结果
    String startPlaceProvince = svo.getStartPlaceProvince();
    List<HAddress> startAddress =null;
    List<HAddress> endAddress =null;

    String endPlaceProvince = svo.getEndPlaceProvince();
    //
    if(null!=startPlaceProvince){
      startAddress =  addressMapper.selectByParams(startPlaceProvince,svo.getStartPlaceCity(),null);
      if(null==startAddress||startAddress.size()==0){
        FleaPage<HProduct> result = new FleaPage<HProduct>();
        return result;
      }
      svo.setStartAdress(startAddress);
    }
    if(null!=endPlaceProvince){
      endAddress =  addressMapper.selectByParams(endPlaceProvince,svo.getEndPalceCity(),null);
      if(null==endAddress||endAddress.size()==0){
        FleaPage<HProduct> result = new FleaPage<HProduct>();
        return result;
      }
      svo.setEndAdress(endAddress);
    }
    RowBounds rowBounds = new RowBounds(curPage, pageSize);
    String orgId = FleaOrgUtils.getCurrentUserDeptUuid(request);
    svo.setOrgId(orgId);
    List<HProduct> pageData = productMapper.selectPagingByOrgConditon(rowBounds,svo);
    FleaPage<HProduct> result = new FleaPage<HProduct>(pageData);
    return result;
  }

  @Override
  public HProduct queryById(String id) {
    // 获取产品
    HProduct product = productMapper.selectByPrimaryKey(id);
    return product;
  }

  @Override
  public boolean save(String jsonString, String userId) throws Exception {
    boolean resultBoolean;
    JSONObject jsonObject = JSON.parseObject(jsonString);
    // 添加产品对象
    HProduct product = JSON.parseObject(jsonString, HProduct.class);
    logger.info("产品对象：{}", product);
    String productId = product.getId();
    // 添加产品的时候product必须为空，添加和修改不在一起
    if (StringUtil.isEmpty(productId)) {
      productId = FleaStringUtils.getGenerateUUID();
      product.setId(productId);
      product.setStatus(HConstant.HCLV_PRODUCT_SALE_STATUS_BOOK);
      logger.info("设置产品为预售：{}", product.getStatus());
    }

    /**
     * 添加出发地址，目的地址
     */
    Map<String, HAddress> place = getProductAddress(productId, userId, product.getStartPlaceProvince(), product.getStartPlaceCity(), product.getEndPlaceProvince(), product.getEndPalceCity());
    HAddress startPlace = place.get("startPlace");
    startPlace.setUuid(productId);
    addressMapper.insertSelective(startPlace);
    logger.info("添加产品出发地:{}", startPlace);
    HAddress endPlace = place.get("endPlace");
    endPlace.setUuid(productId);
    addressMapper.insertSelective(endPlace);
    logger.info("添加产品目的地:{}", endPlace);
    product.setStartPlace(startPlace.getId());
    product.setEndPlace(endPlace.getId());


    OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
    // 设置是哪个服务组织结构
    product.setUuid(dept.getDeptUuid());
    product.setCreateUser(userId);
    logger.info("将要添加的产品:{}", product);
    int resultInt = productMapper.insertSelective(product);

    if (resultInt <= 0) {
      logger.error("产品添加失败");
      throw new Exception("产品添加失败！");
    }

    // 添加产品宣传图片对象
    HResourceRelation jsonRelation = JSON.parseObject(jsonObject.get("image").toString(), HResourceRelation.class);
    jsonRelation.setUuid(productId);
    List<HResourceRelation> prelations = new ArrayList<>();
    prelations.add(jsonRelation);


    boolean imageResult = resourceRelationService.saveImagesRelation(
        prelations, userId);
    if (!imageResult) {
      logger.error("产品图片添加失败,产品图片：{}", prelations);
      throw new Exception("产品图片添加失败！");
    }

    // 添加行程
    Map<String, Object> tripAndSpotRelationMap = getTripAndSpotRelationData(jsonObject, productId, userId);
    @SuppressWarnings("unchecked")
    List<HTrip> trips = (List<HTrip>) tripAndSpotRelationMap.get("trips");
    if(null!=trips&&trips.size()>0){
      resultBoolean = tripService.save(trips);
      if (!resultBoolean) {
        logger.error("行程添加失败，行程对象：{}", trips);
        throw new Exception("行程添加失败！");
      }
      /**
       * 行程相关图片资源
       */
      @SuppressWarnings("unchecked")
      List<HResourceRelation> relations = (List<HResourceRelation>) tripAndSpotRelationMap.get("resourceRelation");

      resultBoolean = resourceRelationService.saveImagesRelation(relations, userId);
      if (!resultBoolean) {
        logger.error("行程添加图片资源失败,行程图片：{}", relations);
        throw new Exception("行程添加图片资源失败！");
      }
    }

    // 添加行程与景点之间的关系
    /*
     * @SuppressWarnings("unchecked") List<HTripSpotsRelation> spotRelations
     * = (List<HTripSpotsRelation>) tripAndSpotRelationMap.get("spots");
     *
     * resultBoolean = tripSpotRelationService.save(spotRelations); if
     * (!resultBoolean) { throw new Exception("行程与景点关系添加失败！"); }
     */
    // 添加说明
    resultBoolean = explainService.save(getExplainData(jsonObject, null, productId, userId));
    if (!resultBoolean) {
      logger.error("说明添加失败,说明信息：{}", getExplainData(jsonObject, null, productId, userId));
      throw new Exception("说明添加失败！");
    }
    // 添加班期
   /*     resultBoolean = timetableService.save(getTimetableData(jsonObject, productId, userId));
        if (!resultBoolean) {
            logger.error("班期添加失败，班期信息：{}", getTimetableData(jsonObject, productId, userId));
            throw new Exception("班期添加失败！");
        }*/


    return true;
  }

  @Override
  public ServerResponse<String> update(String jsonString, String userId)
      throws Exception {
    HProduct entity = JSONObject.parseObject(jsonString, HProduct.class);
    String productId = entity.getId();
    if (StringUtil.isEmpty(productId)) {
      logger.error("缺少产品id,产品ID:{}", productId);
      return ServerResponse.createByErrorMessage("缺少产品id！");
    }

    // 更新产品
    HProduct product = this.queryById(productId);
    if (null == product) {
      logger.debug("要更新的产品不存在,产品ID:{}", productId);
      return ServerResponse.createByErrorMessage("产品不存在！");
    }

    if (!HConstant.HCLV_PRODUCT_SALE_STATUS_BOOK.equals(product.getStatus())&&!HConstant.HCLV_PRODUCT_SALE_STATUS_LOAD.equals(product.getStatus())) {
      logger.debug("产品不在预售状态，不可进行修改，当前产品状态：{},产品ID:{}", product.getStatus(), product.getId());
      return ServerResponse
          .createByErrorMessage("产品不在预售状态，不可进行修改，如需修改，请先下架产品");
    }

    // update出发地址和目的地址

    /**
     * update出发地址，目的地址
     */
    String startPlaceId = entity.getStartPlace();
    String startPlaceProvince = entity.getStartPlaceProvince();
    String startCity = entity.getStartPlaceCity();

    String endPlaceId = entity.getEndPlace();
    String endProvince = entity.getEndPlaceProvince();
    String endCity = entity.getEndPalceCity();

    Map<String, HAddress> place;
    HAddress start = hAddressMapper.selectByPrimaryKey(startPlaceId);
    HAddress end = hAddressMapper.selectByPrimaryKey(endPlaceId);
    if (start == null || end == null) {
      //新建
      place = getProductAddress(productId, userId, startPlaceProvince, startCity, endProvince, endCity);
      HAddress startPlaceEntity = place.get("startPlace");
      addressMapper.insertSelective(startPlaceEntity);
      HAddress endPlace = place.get("endPlace");
      addressMapper.insertSelective(endPlace);
    } else {
      //更新地址
      start.setModifyUser(userId);
      start.setProvince(startPlaceProvince);
      start.setCity(startCity);
      start.setId(startPlaceId);
      hAddressMapper.updateByPrimaryKeySelective(start);

      end.setModifyUser(userId);
      end.setProvince(endProvince);
      end.setCity(endCity);
      end.setId(endPlaceId);
      hAddressMapper.updateByPrimaryKeySelective(end);
    }


    // TODO,修改产品

    entity.setModifyUser(userId);

    boolean result = productMapper.updateByPrimaryKey(entity) == 1;
    if (!result) {
      logger.error("产品修改失败,产品Id:{}", entity.getId());
      throw new Exception("产品修改失败！");
    }

    // TODO 行程修改，先删除，删除图片，再添加，因为产品可能会改变几天
    JSONObject jsonObject = JSON.parseObject(jsonString);
    Map<String, Object> tripAndSpotRelationMap = getTripAndSpotRelationData(
        jsonObject, productId, userId);

    // 删除与行程相关的图片
    List<HTrip> newTrips = (List<HTrip>) tripAndSpotRelationMap.get("trips");
    if(null!=newTrips && newTrips.size()>0){
      List<HTrip> oldTrips = tripService.getByProductId(productId);
      List<String> ids = getTripIds(oldTrips);
      boolean delResult = resourceRelationService.deleteByUuids(ids);
      // 删除行程
      if (!delResult) {
        logger.error("产品修改失败,产品Id:{}", productId);
        throw new Exception("行程图片删除失败！");
      }
      List<String> por = new ArrayList<>();
      por.add(productId);
      result = tripService.deleteByProductIds(por, userId);
      if (!result) {
        logger.error("行程删除失败,产品Id:{},", productId);
        throw new Exception("行程删除失败！");
      }

      // 获取行程，save

//          @SuppressWarnings("unchecked")
//          List<HTrip> newTrips = (List<HTrip>) tripAndSpotRelationMap.get("trips");
      boolean tripResult = tripService.save(newTrips);
      if (!tripResult) {
        logger.error("行程添加失败,行程对象:{}", newTrips);
        throw new Exception("行程添加失败！");
      }
      // 获取行程图片，save
      @SuppressWarnings("unchecked")
      List<HResourceRelation> tripImageRelations = (List<HResourceRelation>) tripAndSpotRelationMap
          .get("resourceRelation");
      boolean tripResRelationResult = resourceRelationService.saveImagesRelation(tripImageRelations, userId);
      if (!tripResRelationResult) {
        logger.error("行程图片添加失败,行程图片:{}", tripImageRelations);
        throw new Exception("行程图片添加失败！");
      }
    }

    // TODO 班期修改，班期不可以删除，需要
    // 根据产品id删除班期

//        result = timetableService.deleteByProductIds(por, userId);
//        if (!result) {
//            logger.error("班期删除失败,产品id:{}", productId);
//            throw new Exception("班期删除失败！");
//        }
//
//        List<HTimeTable> timeTables = getTimetableData(jsonObject, productId, userId);
//        result = timetableService.save(timeTables);
//        if (!result) {
//            logger.error("班期添加失败,班期对象:{}", timeTables);
//            throw new Exception("班期添加失败！");
//        }

    // TODO 说明信息
    List<HExplain> explains = explainService.getByProductId(productId);
    explains = getExplainData(jsonObject, explains, productId, userId);
    for (HExplain hExplain : explains) {
      result = explainService.update(hExplain);
      if (!result) {
        logger.error("说明修改失败,说明信息：{}", hExplain);
        throw new Exception("说明修改失败！");
      }
    }

    return ServerResponse.createBySuccessMessage("修改成功");
  }

  private List<String> getTripIds(List<HTrip> oldTrips) {
    List<String> ids = new ArrayList<>();
    for (HTrip hTrip : oldTrips) {
      ids.add(hTrip.getId());
    }
    return ids;
  }

  @Override
  public ServerResponse<Boolean> delete(String ids, String userId) throws Exception {
    OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
    if (dept == null) {
      logger.error("未获取操作人部门信息");
      return ServerResponse.createByErrorMessage("未获取操作人部门信息，不可进行删除");
    }
    List<String> idsArray = JSON.parseArray(ids, String.class);
    List<HProduct> delOldList = productMapper.findByIdsAndDeptId(dept.getDeptUuid(), idsArray);
    for (HProduct hProduct : delOldList) {
      if (!HConstant.HCLV_PRODUCT_SALE_STATUS_BOOK.equals(hProduct.getStatus())&&!HConstant.HCLV_PRODUCT_SALE_STATUS_LOAD.equals(hProduct.getStatus())) {
        logger.info("部分产品为非预售状态或下架状态，不可进行删除,产品id:{},产品状态：{}", hProduct.getId(), hProduct.getStatus());
        return ServerResponse.createByErrorMessage("部分产品为非预售状态或下架状态，不可进行删除");
      }
    }


    if (productMapper.delete(idsArray) <= 0) {
      logger.error("产品删除失败，产品ID:{}", idsArray);
      throw new Exception("产品删除失败！");
    }
    // 根据产品id删除行程
    if (!tripService.deleteByProductIds(idsArray, userId)) {
      logger.error("行程删除失败，产品ID:{}", idsArray);
//            throw new Exception("行程删除失败！");
    }
    // 根据产品id删除行程与景点关系
	/*	if (!tripSpotRelationService.deleteByProductIds(ids, userId)) {
			throw new Exception("行程与景点关系删除失败！");
		}*/
    // 根据产品id删除班期
    if (!timetableService.deleteByProductIds(idsArray, userId)) {
      logger.error("班期删除失败，产品ID:{}", idsArray);
//            throw new Exception("班期删除失败！");
    }
    // 根据产品id删除说明
    if (!explainService.deleteByProductIds(ids, userId)) {
      logger.error("说明删除失败，产品ID:{}", ids);
//            throw new Exception("说明删除失败！");
    }
    return ServerResponse.createBySuccess("删除成功", true);
  }

  @Override
  public JSONObject queryDetailById(String id) {
    JSONObject resultJsonObject = new JSONObject();

    HProduct product = productMapper.selectByPrimaryKey(id);

    String typeCode  =product.getType();

    List<WebDict> types = HclvDictUtil.getTourism();
    for (WebDict web: types
    ) {
      if(web.getDictCode().equals(typeCode)){
        product.setTypeName(web.getDictName());
      }
    }

    String deptName = FleaOrgUtils.getOrgDeptByDeptUuid(product.getUuid()).getDeptName();

    List<HExplain> explains = explainService.getByProductId(id);
    List<HTimeTable> timetables = timetableService.getByProductId(id);
    List<HTrip> trips = tripService.getByProductId(id);
    HAddress startPalce = addressMapper.selectByPrimaryKey(product.getStartPlace());


    WebDict province = HclvDictUtil.getCodeName(startPalce.getProvince(), Const.D_REGION);
    String pronvinceName = null==province?"未找到":province.getDictName();
    WebDict city = HclvDictUtil.getCodeName(startPalce.getCity(), Const.D_REGION);
    startPalce.setProvinceName(pronvinceName);
    String cityName = null==city?"未找到":city.getDictName();
    startPalce.setCityName(cityName);



    HAddress endPlace = addressMapper.selectByPrimaryKey(product
        .getEndPlace());
    WebDict endProvince = HclvDictUtil.getCodeName(endPlace.getProvince(), Const.D_REGION);
    String endPronvinceName = null==endProvince?"未找到":endProvince.getDictName();
    WebDict endCity = HclvDictUtil.getCodeName(endPlace.getCity(), Const.D_REGION);
    endPlace.setProvinceName(endPronvinceName);
    String endCityName = null==endCity?"未找到":endCity.getDictName();
    endPlace.setCityName(endCityName);

    //获取上传行程的文档路径
    String travelTripFileId = product.getFileTripId();

    if(!StringUtil.isEmpty(travelTripFileId)){
      WebFileupload file =  webFileuploadMapper.selectByPrimaryKey(travelTripFileId);
     String filePath =  file.getFileDir()+file.getNewFileName();
      product.setTripFilePath(filePath);
      product.setOriginalFileName(file.getFileName());
    }



    List<HTripSpotsRelation> tripSpotRelationTmp;
    JSONObject tripJsonObject;
    JSONArray tripJsonArray = new JSONArray();
    for (HTrip hTrip : trips) {
      tripSpotRelationTmp = tripSpotRelationService.getByTripId(hTrip
          .getId());
      List<HResourceRelation> tempRe = resourceRelationService
          .findFilePathByUuid(hTrip.getId());
      if (null != tempRe && tempRe.size() > 0) {
        hTrip.setImagePath(tempRe.get(0).getPath());
      }
      tripJsonObject = (JSONObject) JSON.toJSON(coverToQianDuan(hTrip));
      tripJsonObject.put("spot", JSON.toJSON(tripSpotRelationTmp));
      tripJsonArray.add(tripJsonObject);
    }
    List<HResourceRelation> resources = resourceRelationService
        .findFilePathByUuid(id);

    resultJsonObject.put("product", JSON.toJSON(product));
    resultJsonObject.put("explains", JSON.toJSON(explains));
    resultJsonObject.put("timetables", JSON.toJSON(timetables));
    resultJsonObject.put("trip", tripJsonArray);
    resultJsonObject.put("startPlace", startPalce);
    resultJsonObject.put("endPlace", endPlace);
    resultJsonObject.put("resources", resources);
    resultJsonObject.put("gongYingShang", deptName);
    logger.info("产品详情：{}", resultJsonObject);
    return resultJsonObject;
  }

  /**
   * 获取行程，已经行程景点的关联关系
   *
   * @description TODO
   * @methodName getTripAndSpotRelationData
   * @param
   * @returnType Map<String , Object>
   * @throw
   */
  private Map<String, Object> getTripAndSpotRelationData(
      JSONObject jsonObject, String productId, String userId) {
    JSONObject jsonObjectTmp;
    HTrip tripTmp;
    List<HTrip> tripList = new ArrayList<>();
    List<HTripSpotsRelation> spotList = new ArrayList<>();
    List<HResourceRelation> tripPicture = new ArrayList<>();
    Map<String, Object> result = new HashMap<>();
    JSONArray tripJson = jsonObject.getJSONArray("trip");
    if(null==tripJson){
      result.put("trips", tripList);
      result.put("spots", spotList);
      result.put("resourceRelation", tripPicture);
      logger.info("行程：{}，行程图片：{}", tripList, tripPicture);
      return result;
    }
    JSONArray jsonArray = JSONObject.parseArray(tripJson.toString());

    for (Object aJsonArray : jsonArray) {
      jsonObjectTmp = (JSONObject) aJsonArray;
      ProductTripVo temTripVo = JSONObject.parseObject(
          jsonObjectTmp.toString(), ProductTripVo.class);
      // tripTmp = JSON.parseObject(jsonObjectTmp.toString(),
      // HTrip.class);
//      String tripDesc = jsonObjectTmp.getString("description");
//      JSONObject image = jsonObjectTmp.getJSONObject("resource");
//      String path = image.getString("path");
//      String resourceId = image.getString("resouceId");
      tripTmp = temTripVo.getHTrip();
      String tripTmpId = FleaStringUtils.getGenerateUUID();
      // tripTmp.setId(FleaStringUtils.getGenerateUUID());
      tripTmp.setId(tripTmpId);
//      tripTmp.setDescription(tripDesc);
      tripTmp.setProductId(productId);
      // 只有第一次创建的时候设置,修改的时候不变
      tripTmp.setCreateUser(userId);
      tripTmp.setModifyUser(userId);
      // 景点和产品关联表
      /*
       * spotList =
       * JSONArray.parseArray(jsonObjectTmp.getJSONArray("spot")
       * .toString(), HTripSpotsRelation.class); for (int j = 0; j <
       * spotList.size(); j++) {
       * spotList.get(j).setId(FleaStringUtils.getGenerateUUID());
       * spotList.get(j).setTripId(tripTmp.getId());
       * spotList.get(j).setCreateUser(userId); }
       */
      tripList.add(tripTmp);

      HResourceRelation temRelation = temTripVo.getImageRelation();
//      temRelation.setPath(path);
//      temRelation.setResouceId(resourceId);
      temRelation.setUuid(tripTmpId);
      tripPicture.add(temRelation);

    }
    result.put("trips", tripList);
    result.put("spots", spotList);
    result.put("resourceRelation", tripPicture);
    logger.info("行程：{}，行程图片：{}", tripList, tripPicture);
    return result;
  }

  /**
   * 从request请求中获取说明信息
   *
   * @description TODO
   * @methodName getExplainData
   * @param
   * @returnType List<HExplain>
   * @throw
   */
  private List<HExplain> getExplainData(JSONObject jsonObject,
      List<HExplain> explains, String productId, String userId) {
    /**
     * 原始请求中的说明信息：说明信息如何区分预定须知和费用说明
     */
    JSONObject explainObject = (JSONObject) jsonObject
        .getJSONObject("explain");
    // 添加方法中 explains 为null值
    if (explains != null && explains.size() > 0) {
      String description;
      for (HExplain hExplain : explains) {
        description = explainObject.getString(hExplain.getUuid());
        if (!StringUtil.isEmpty(description)) {
          hExplain.setDescription(description);
          hExplain.setModifyUser(userId);
        }
      }
      return explains;
    }
    HExplain explainTmp;
    List<HExplain> explainList = new ArrayList<HExplain>();

    String key;

    for (String s : explainObject.keySet()) {
      explainTmp = new HExplain();
      explainTmp.setId(FleaStringUtils.getGenerateUUID());
      explainTmp.setProductId(productId);
      key = s;
      explainTmp.setUuid(key);
      explainTmp.setDescription(explainObject.getString(key));
      explainTmp.setCreateUser(userId);
      explainTmp.setModifyUser(userId);
      explainList.add(explainTmp);
    }
    return explainList;
  }

  private List<HTimeTable> getTimetableData(JSONObject jsonObject, String productId, String userId) {
    List<HTimeTable> result = JSON.parseArray(jsonObject.getJSONArray("timetable").toString(), HTimeTable.class);
    for (HTimeTable hTimeTable : result) {
      if (StringUtil.isEmpty(hTimeTable.getId())) {
        hTimeTable.setId(FleaStringUtils.getGenerateUUID());
      }
      if (StringUtil.isEmpty(hTimeTable.getProductId())) {
        hTimeTable.setProductId(productId);
      }
      if (StringUtil.isEmpty(hTimeTable.getCreateUser())) {
        hTimeTable.setCreateUser(userId);
      }
      hTimeTable.setModifyUser(userId);

    }
    return result;
  }

  @Override
  public FleaPage<HProduct> queryDetailForSearch(ProductSearchVo pvo) {
    return null;
  }

  /**
   * 公共查询获取产品接口
   */
  @Override
  public FleaPage<HProduct> queryDetailForSearch(HttpServletRequest request, Integer curPage, Integer pageSize, ProductSearchVo pvo) {
    RowBounds rowBounds = new RowBounds(curPage, pageSize);
    if (null == pvo) {
      pvo = new ProductSearchVo();
    }
    // 1、筛选出发城市地址
    String startProvince = pvo.getStartPlaceProvince();
    String startCity = pvo.getStartPlaceCity();
    List<HAddress> startAdress = null;
    if (StringUtils.isNotEmpty(startProvince)) {
      startAdress = addressMapper.selectByParams(startProvince, startCity, null);
      if (CollectionUtils.isEmpty(startAdress)) {
        return new FleaPage<>();
      }
    }


    // 2、筛选目的城市地址
    String endProvince = pvo.getEndPlaceProvince();
    String endCity = pvo.getEndPalceCity();
    List<HAddress> endAdress = null;
    if (StringUtils.isNotEmpty(endProvince)) {
      endAdress = addressMapper.selectByParams(endProvince,
          endCity, null);
      if (CollectionUtils.isEmpty(endAdress)) {
        return new FleaPage<>();
      }
    }
    // 3、筛选景点
    // 根据多个景点的名字进行匹配，可使用,记性分割
    String spot = pvo.getSpots();
    String[] spotNames;
    if (StringUtils.isNotBlank(spot)) {
      spotNames = spot.split(",");
      /**
       * 使用like进行匹配，进行多匹配，获取多个景点，景点与线路关联，线路与产品进行关联
       */
      List<HSpot> spots;
      if (!spotNames[0].equals("")) {

        spots = spotMapper.selectByNames(spotNames);
        if (CollectionUtils.isEmpty(spots)) {
          return new FleaPage<>();
        }
        List<HlineSpotRelation> relations = lineSpotRelationMapper.selectBySpots(spots);
        if (CollectionUtils.isEmpty(relations)) {
          relations = null;
        }
        pvo.setLineRelations(relations);
      }
    }

    // 获取所有产品，已经获取到了 线路，获取与线路相关的产品

    // 将所有的查询条件参数添加到查询对象中
    pvo.setEndAdress(endAdress);
    pvo.setStartAdress(startAdress);

    pvo.setSaleStatus(HConstant.HCLV_PRODUCT_SALE_STATUS_ONSALE);
    List<HProduct> pageData = productMapper.selectForSearch(rowBounds, pvo);
    FleaPage<HProduct> result = new FleaPage<>(pageData);

    if (null != pageData && pageData.size() > 0) {
      pageData = convetCodeTOName(pageData);
    }

//		FleaPage<HProduct> result = new FleaPage<HProduct>();
    result.setCurPageData(pageData);
    return result;

  }

  @Override
  public ServerResponse<List<HProduct>> findByDeptId(String deptUuid) {
    return ServerResponse.createBySuccess(productMapper
        .findByDeptId(deptUuid));
  }

  @Override
  public FleaPage<HProduct> queryDetailForSearchByOrgId(
      HttpServletRequest request, Integer curPage, Integer pageSize, ProductSearchVo pvo) {
    RowBounds rowBounds = new RowBounds(curPage, pageSize);
    String serviceOrgId = FleaOrgUtils.getCurrentUserDeptUuid(request);

    // 1、筛选出发城市地址
    String startProvince = pvo.getStartPlaceProvince();
    String startCity = pvo.getStartPlaceCity();
    List<HAddress> startAdress = addressMapper.selectByParams(
        startProvince, startCity, null);
    // 2、筛选目的城市地址
    String endProvince = pvo.getEndPlaceProvince();
    String endCity = pvo.getEndPalceCity();
    List<HAddress> endAdress = addressMapper.selectByParams(endProvince,
        endCity, null);
    // 3、筛选景点
    // 根据多个景点的名字进行匹配，可使用,记性分割
    String[] spotNames = null;
    String spot = pvo.getSpots();
    if (null != spot) {
      spotNames = spot.split(",");
    }

    /**
     * 使用like进行匹配，进行多匹配，获取多个景点，景点与线路关联，线路与产品进行关联
     */
    List<HSpot> spots = null;/* spotMapper.selectByNames(spotNames);saleStatus */

    List<HlineSpotRelation> relations = lineSpotRelationMapper.selectBySpots(spots);

    // 获取所有产品，已经获取到了 线路，获取与线路相关的产品

    // 将所有的查询条件参数添加到查询对象中
    pvo.setEndAdress(endAdress);
    pvo.setStartAdress(startAdress);
    pvo.setLineRelations(relations);
    pvo.setServiceOrgId(serviceOrgId);

    List<HProduct> pageData = productMapper.selectForSearch(rowBounds, pvo);
    if (null != pageData && pageData.size() > 0) {
      pageData = convetCodeTOName(pageData);
    }

    FleaPage<HProduct> result = new FleaPage<>();
    result.setCurPageData(pageData);
    return result;
  }

  /**
   * 将字符字典中的代码转换为Name
   *
   * @description TODO
   * @methodName convetCodeTOName
   * @param
   * @returnType List<HProduct>
   * @throw
   */
  private List<HProduct> convetCodeTOName(List<HProduct> souceList) {
    // 旅游类型：
    List<WebDict> pros = HclvDictUtil.getTourism();
    if (pros == null) {
      return null;
    }
    List<HProduct> target = new ArrayList<>();
    for (HProduct p : souceList) {
      HLine hLine = hLineMapper.selectByPrimaryKey(p.getLineId());
      p.setLineName(hLine == null ? null : hLine.getName());
      OrgUser user = orgUserMapper.selectByPrimaryKey(p.getCreateUser());
      p.setCreateUserName(user.getUserName());

      for (WebDict type : pros) {
        if (type.getDictCode().equals(p.getType())) {
          p.setTypeName(type.getDictName());
          target.add(p);
          break;
        }

      }
    }

    return target;
  }

  private HTrip coverToQianDuan(HTrip hTrip) {
    if (null == hTrip) {
      return null;
    } else {

      if ("Y".equals(hTrip.getIsAbroad())) {
        hTrip.setIsAbroad("true");
      } else {
        hTrip.setIsAbroad("false");
      }
      if (("Y").equals(hTrip.getBus())) {
        hTrip.setBus("true");
      } else {
        hTrip.setBus("false");
      }
      if (("Y").equals(hTrip.getTrain())) {
        hTrip.setTrain("true");
      } else {
        hTrip.setTrain("false");
      }
      if (("Y").equals(hTrip.getShip())) {
        hTrip.setShip("true");
      } else {
        hTrip.setShip("false");
      }
      if (("Y").equals(hTrip.getSubway())) {
        hTrip.setSubway("true");
      } else {
        hTrip.setSubway("false");
      }
      if (("Y").equals(hTrip.getHsubway())) {
        hTrip.setHsubway("true");
      } else {
        hTrip.setHsubway("false");
      }
      if (("Y").equals(hTrip.getPlane())) {
        hTrip.setPlane("true");
      } else {
        hTrip.setPlane("false");
      }
      if (("Y").equals(hTrip.getBreakfast())) {
        hTrip.setBreakfast("true");
      } else {
        hTrip.setBreakfast("false");
      }
      if (("Y").equals(hTrip.getLunch())) {
        hTrip.setLunch("true");
      } else {
        hTrip.setLunch("false");
      }
      if (("Y").equals(hTrip.getDinner())) {
        hTrip.setDinner("true");
      } else {
        hTrip.setDinner("false");
      }
      if (("Y").equals(hTrip.getNothing())) {
        hTrip.setNothing("true");
      } else {
        hTrip.setNothing("false");
      }
      if (("Y").equals(hTrip.getAircraft())) {
        hTrip.setAircraft("true");
      } else {
        hTrip.setAircraft("false");
      }
      return hTrip;
    }
  }

  private Map<String, HAddress> getProductAddress(String productId,
      String userId, String startProvince, String startCity,
      String endProvince, String endCity) {

    HAddress startPalce = new HAddress();
    String startPalceId = FleaStringUtils.getGenerateUUID();
    startPalce.setId(startPalceId);
    startPalce.setCity(startCity);
    startPalce.setProvince(startProvince);
    startPalce.setUuid(productId);
    startPalce.setCreateUser(userId);

    HAddress endplacy = new HAddress();
    String endPalceId = FleaStringUtils.getGenerateUUID();
    endplacy.setId(endPalceId);
    endplacy.setCity(endCity);
    endplacy.setProvince(endProvince);
    endplacy.setUuid(productId);
    endplacy.setCreateUser(userId);

    Map<String, HAddress> result = new HashMap<>();
    result.put("startPlace", startPalce);
    result.put("endPlace", endplacy);
    return result;
  }

  @Override
  public ServerResponse<Boolean> updateToOnSale(String ids, String userId) throws Exception {
    OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
    if (dept == null) {
      logger.error("未获取操作人部门信息");
      return ServerResponse.createByErrorMessage("未获取操作人部门信息，不可进行操作");
    }
    List<String> idsArray = JSON.parseArray(ids, String.class);
    List<HProduct> oldList = productMapper.findByIdsAndDeptId(dept.getDeptUuid(), idsArray);
    for (HProduct hProduct : oldList) {
      hProduct.setModifyUser(userId);
      hProduct.setStatus(HConstant.HCLV_PRODUCT_SALE_STATUS_ONSALE);
      boolean result = productMapper.updateByPrimaryKey(hProduct) == 1;
      if (!result) {
        logger.error("产品上架失败,产品：{}", hProduct);
        throw new Exception("产品上架失败！");
      }
    }

    return ServerResponse.createBySuccess("上架操作成功", true);
  }

  @Override
  public ServerResponse<Boolean> updateToOndown(String ids, String userId) throws Exception {
    OrgDept dept = FleaOrgUtils.getCurrentUserDept(userId);
    if (dept == null) {
      logger.error("未获取操作人部门信息");
      return ServerResponse.createByErrorMessage("未获取操作人部门信息，不可进行操作");
    }
    List<String> idsArray = JSON.parseArray(ids, String.class);
    List<HProduct> oldList = productMapper.findByIdsAndDeptId(dept.getDeptUuid(), idsArray);
    for (HProduct hProduct : oldList) {
      hProduct.setModifyUser(userId);
      hProduct.setStatus(HConstant.HCLV_PRODUCT_SALE_STATUS_LOAD);
      boolean result = productMapper.updateByPrimaryKey(hProduct) == 1;
      if (!result) {
        logger.error("产品下架失败,产品：{}", hProduct);
        throw new Exception("产品下架失败！");
      }
    }

    return ServerResponse.createBySuccess("下架操作成功", true);
  }

}
